package com.admin.controller;


import com.admin.entity.Terminal;
import com.admin.entity.TerminalKey;
import com.admin.enums.TerminalLockType;
import com.admin.excelList.TerminalList;
import com.admin.requestBody.TerminalPasswordRequest2;
import com.admin.service.IAdminService;
import com.admin.service.ITerminalService;
import com.admin.service.impl.TerminalKeyServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.excel.ExcelUtil;
import com.excel.TerminalInfo;
import com.util.ExcelUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 终端模块
 *
 * @author marisheng
 * @since 2019-11-15
 */
@RestController
@RequestMapping("/admin/terminal")
public class TerminalController {

    @Autowired
    private ITerminalService terminalService;

    @Autowired
    private TerminalKeyServiceImpl terminalKeyService;

    @Autowired
    private IAdminService adminService;

    @Autowired
    @SuppressWarnings("all")
    private HttpServletResponse response;
    /**
     * 分页查询
     *
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @RequestMapping("queryTerminalKey")
    public ResponseBean queryTerminalKeyC(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map) {
        IPage iPage = terminalService.queryTerminalKeyS(page, limit, map);
        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }


    /**
     * 终端管理查询表格字段
     *
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @GetMapping("/selectTerminal")
    public ResponseBean selectTerminal(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map) {

        IPage iPage = terminalService.selectTerminal(page, limit, map);
        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 锁定终端  需要两个参数  terminalId和terminalLock
     *
     * @param terminal_id   终端id
     * @param terminal_lock 修改后的状态
     * @return
     */
    @GetMapping("/updateLockById")
    public ResponseBean updateLockById(@RequestParam("terminal_id") int terminal_id, @RequestParam("terminal_lock") String terminal_lock,@RequestParam(value = "station_bh",defaultValue = "")String station_bh,@RequestParam("admin_id")String adminId) {
        if(!"".equals(station_bh)) {
            int updateId = terminalService.selectAdminIdByStationBh(station_bh);
            int i = adminService.selectQuanxian(updateId, adminId);
            if (i == 500) {
                return new ResponseBean(403, "权限不足", null);
            }
        }
        int n = terminalService.updateLockById(terminal_lock, terminal_id);
        return ResponseBean.vo(n, 0);
    }


    /**
     * 删除终端
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "remove/terminal", method = RequestMethod.DELETE)
    public ResponseBean removeTerminalC(@RequestBody Integer id) {

        if (id == null) {
            return new ResponseBean(500, "操作失败", "");
        }
        boolean b = terminalService.removeById(id);
        return ResponseBean.vo(b, 0);
    }

    /**
     * 导出excel
     * @param
     * @throws IOException
     */
    @RequestMapping(value = "writeExcel", method = RequestMethod.GET)
    public void writeExcel( @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map, String
            macfj) throws IOException {

        ResponseBean responseBean = ifQueryIpMacFjAll(map, macfj);

        if (responseBean != null) {
            return;
        }

        IPage iPage = terminalService.excelTerminal(page, limit, map);

        List<TerminalInfo> list = iPage.getRecords();
        String fileName = "Termain Excel";
        String sheetName = "sheet";

        ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName, new TerminalInfo())
                .finish();

//        return new ResponseBean(200,"操作成功","");
    }

    /**
     * 终端列表查询所有或模糊查 房间号 /mac/ ip地址
     *
     * @param page
     * @param limit
     * @param map
     * @param macfj
     * @return
     */
    @PostMapping("/queryIpMacFjAll")
    public ResponseBean queryIpMacFjAll(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map, String
            macfj) {

        ResponseBean responseBean = ifQueryIpMacFjAll(map, macfj);
        if (responseBean != null) {
            return responseBean;
        }

        IPage iPage = terminalService.queryIpMacFjAll(page, limit, map);
        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }


    /**
     * 修改终端编辑
     *
     * @param terminal
     * @return
     */
    @PutMapping("/modifyByIdIpMacFj")
    public ResponseBean updateByIdIpMacFj(@RequestBody Terminal terminal) {
        ResponseBean responseBean1 = ifByIdTerminal(terminal);
        if (responseBean1 != null) {
            return responseBean1;
        }

        boolean b = terminalService.updateById(terminal);
        if (b == true) {
            return new ResponseBean(200, "修改成功", null);
        } else {
            return new ResponseBean(500, "修改失败", null);
        }
    }

    /**
     * 站点管理 终端统计
     *
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @GetMapping("/querysystemStatistics")
    public ResponseBean querysystemStatistics(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map) {
        String stationId = (String) map.get("terminalStation");
        if (stationId == null || stationId == "") {
            return new ResponseBean(500, "操作失败", "请输入正确的查询条件");
        }
        IPage result = terminalService.querysystemStatistics(page, limit, map);
        System.out.println(result.getTotal());
        System.out.println("laila");
        return new ResponseBean(0, result.getTotal(), result.getRecords());
    }


    /**
     * 站点管理 终端列表 解绑
     *
     * @param terminalId
     * @return
     */
    @PutMapping("/updateUntyingTerminal")
    public ResponseBean updateUntyingTerminal(Integer terminalId) {
        if (terminalId == null || terminalId == 0) {
            return new ResponseBean(500, "操作失败", "未获取终端Id");
        }
        int n = terminalService.updateUntyingTerminal(terminalId);
        return ResponseBean.vo(n, 0);
    }

    /**
     * 分组列表 操作查看每个分组的所有终端
     *
     * @param page  页
     * @param limit 条数据
     * @param map   查询参数
     * @return
     */
    @GetMapping("/groupQueryTerminall")
    public ResponseBean groupQueryTerminall(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map, String macfj) {
        ResponseBean responseBean = ifGroupQueryIpMacFjAll(map, macfj);
        if (responseBean != null) {
            return responseBean;
        }

        IPage iPage = terminalService.groupQueryTerminal(page, limit, map);
        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }


    /**
     * 终端统计的上下线使用记录
     *
     * @return
     */
    @RequestMapping("query/startAndEndTime")
    public ResponseBean queryStartAndEndTime(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map) {

        IPage iPage = terminalService.queryStatrtAndEndTime(page, limit, map);

        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }


    /**
     * 通过终端id 查出三个Ip,Mac,房间号
     *
     * @param terminalId
     * @return
     */
    @GetMapping("/byIdTerminal")
    public ResponseBean byIdTerminal(Integer terminalId) {
        if (terminalId == 0) {
            return new ResponseBean(500, "操作失败", "未获取到终端Id");
        }

        Terminal byId = terminalService.getById(terminalId);
        return new ResponseBean(200, "success", byId);
    }


    /**
     * 判断分组点某个分组查询所有终端或模糊查 房间号 /mac/ ip地址 的参数
     */

    public ResponseBean ifGroupQueryIpMacFjAll(Map map, String macfj) {
        String stationId = (String) map.get("terminalStation");
        String groupId = (String) map.get("groupId");
        if (stationId == null || stationId == "" && groupId == null || groupId == "") {
            return new ResponseBean(500, "操作失败", "请输入正确的查询条件");
        }
        boolean f = terminalService.findByStationId(stationId);
        if (f == false) {
            return new ResponseBean(500, "无数据", "无数据");
        }
        if (macfj != null && macfj != "") {
            if (macfj.contains(":") == true) {
                map.put("terminalMac", macfj);
            } else if (macfj.contains(".") == true) {
                map.put("terminalIp", macfj);
            } else {
                map.put("terminalRoom", macfj);
            }
        }
        return null;
    }

    /**
     * 判断终端列表查询所有或模糊查 房间号 /mac/ ip地址 的参数
     */

    public ResponseBean ifQueryIpMacFjAll(Map map, String val) {
        String stationId = (String) map.get("terminalStation");

        if (stationId == null || stationId == "") {
            return new ResponseBean(500, "操作失败", "请输入正确的查询条件");
        }

        boolean f = terminalService.findByStationId(stationId);
        if (f == false) {
            return new ResponseBean(500, "无数据", "无数据");
        }
        if (val != null && val != "") {
            if (val.contains(":") == true) {
                map.put("terminalMac", val);
            } else if (val.contains(".") == true) {
                map.put("terminalIp", val);
            } else {
                map.put("terminalRoom", val);
            }
        }
        return null;
    }


    /**
     * 修改终端编辑的 判断参数
     *
     * @param terminal
     * @return
     */
    public ResponseBean ifByIdTerminal(Terminal terminal) {
        // 判断站点编号是否获取
        if (terminal.getTerminalId() == null) {
            return new ResponseBean(500, "修改失败", "未获取Id");
        }

        // 判断终端ID存在
        Terminal t = terminalService.getById(terminal.getTerminalId());
        if (t == null) {
            return new ResponseBean(500, "操作失败", "请输入正确的修改条件");
        }
        return null;
    }

    /**
     * 设置钟点房密钥授权以及标准房密钥授权
     *
     * @return
     */
    @PostMapping(value = "/TerminalByIdUpdateTermainal_keyByIdupdate", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean TerminalByIdUpdateTermainal_keyByIdupdate(TerminalPasswordRequest2 tp) {
        System.out.println(tp + "sdsd");
        Terminal terminal = terminalService.getById(tp.getTerminalId());
        TerminalKey byId = terminalKeyService.getById(tp.getTerminalKeyId());
        if (tp.getTerminalKeyEndTime() == null) {
            int i = terminalService.TerminalByIdUpdateTermainal_keyByIdupdate(terminal, byId, tp);
            if (i == 403) {
                return new ResponseBean(3, 0, "密钥余额不足!");
            }
            if (i == 1) {
                return new ResponseBean(0, 0, "标准房授权成功");
            }
            return new ResponseBean(2, 0, "标准房授权失败");
        } else {

            int i = terminalService.TerminalByIdUpdateTermainal_keyByIdupdate(terminal, byId, tp);
            if (i == 403) {
                return new ResponseBean(3, 0, "密钥余额不足!");
            }
            if (i == 1) {
                return new ResponseBean(0, 0, "钟点房授权成功");
            }
            return new ResponseBean(2, 0, "钟点房授权失败");
        }
    }

    /**
     * 查找所有的未审核的终端解绑数据
     * @param page
     * @param limit
     * @param tiaojian
     * @return
     */
    @RequestMapping("/selectTerminalShenhe")
    public ResponseBean queryJieChu(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, String tiaojian) {
        IPage result = terminalService.queryJieChu(page, limit, tiaojian);
        return new ResponseBean(0, result.getTotal(), result.getRecords());
    }

    /**
     * 审核：终端解绑
     * @param t
     * @return
     */
    @RequestMapping("/editterminalShenhe")
    public ResponseBean editterminalShenhe(Terminal t) {
        t.setTerminalShenhe("已审核");
        t.setTerminalLock("正常");
        boolean f = terminalService.updateById(t);
        int code = f ? 200 : 500;
        return new ResponseBean(code, null, null);
    }

    @GetMapping("/selectTerminalLockStatus")
    public ResponseBean selectTerminalLockStatus(){
        EnumSet<TerminalLockType> enumSet = EnumSet.allOf(TerminalLockType.class);
        return new ResponseBean(0,"成功",enumSet);
    }

    /**
     * 终端列表的操作分组
     * @param terminal
     * @return
     */
    @RequestMapping(value = "/updateTerminalGroup",method = RequestMethod.PUT)
    public ResponseBean updateTerminalGroup(Terminal terminal){

        boolean b = terminalService.updateById(terminal);
        if (b==false){
            return new ResponseBean(500,"操作失败","修改失败");
        }
        return new ResponseBean(200,"操作成功","修改成功");

    }

    @GetMapping("/excelTerminalList")
    public void excelTerminalList() throws IOException {
        List<TerminalList> list = terminalService.excelTerminalList();
        //Excel工具类 第二个参数是数据列表 第三个参数文件名称
        ExcelUtil2.OutExcel(response,list,"终端列表");
    }

}
